﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace umbraco.ACSExtensions
{
    using System;
    using System.Linq;
    using System.Globalization;
    using umbraco.cms.businesslogic.member;

    public static class UmbracoExtensions
    {
        public static T GetGenericProperty<T>(this Member member, string propertyName, bool failIfNotExist = true)
        {
            var property = member.GenericProperties.SingleOrDefault(p => p.PropertyType.Alias == propertyName);
            if (property == null)
            {
                if (failIfNotExist)
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.InvariantCulture, "The generic property '{0}' does not exist.", propertyName));
                }
                else
                {
                    return default(T);
                }
            }

            try
            {
                return (T)Convert.ChangeType(property.Value, typeof(T), CultureInfo.InvariantCulture);
            }
            catch (FormatException)
            {
                return default(T);
            }
        }

        public static void SetGenericProperty(this Member member, string propertyName, object propertyValue)
        {
            var property = member.GenericProperties.SingleOrDefault(p => p.PropertyType.Alias == propertyName);
            if (property == null)
            {
                throw new InvalidOperationException(
                    string.Format(CultureInfo.InvariantCulture, "The generic property '{0}' does not exist.", propertyName));
            }

            property.Value = propertyValue;
        }
    }
}